package lzy.controller;

import lzy.entity.User;
import lzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;

@Controller
public class LoginController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       HttpSession session,
                       RedirectAttributes redirectAttributes) {
        // 从数据库查找用户
        User user = userService.findByUsername(username);
        
        // 检查用户是否存在
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "账号不存在！");
            return "redirect:/login";
        }
        
        // 验证密码
        if (!userService.authenticate(username, password)) {
            redirectAttributes.addFlashAttribute("error", "账号或密码错误！");
            return "redirect:/login";
        }
        
        // 用户验证成功，将用户信息存入session
        session.setAttribute("user", user);
        
        // 根据用户角色重定向到不同的页面
        switch (user.getRole()) {
            case "ADMIN":
                return "redirect:/admin/system_overview";
            case "PRODUCING":
                return "redirect:/production/farming_management";
            case "PROCESSING":
                return "redirect:/processing/batch_management";
            case "USERB":
                return "redirect:/user/dashboard";
            case "CONSUMER":
                return "redirect:/consumer/index";
            default:
                redirectAttributes.addFlashAttribute("error", "未知的用户角色！");
                return "redirect:/login";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
} 